<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>C++ Tutorial: Operator Overloading</title>
  <meta
 content="C++ Tutorial: Operator Overloading"
 name="description" />
  <meta
 content="C++ Tutorial, Operator Overloading"
 name="keywords" />
  <meta http-equiv="Content-Type"
 content="text/html; charset=ISO-8859-1" />
  <link type="text/css" rel="stylesheet" href="../images/bogostyleWidePre.css" />
</head>
<body>
<div id="page" align="center">
<div id="content" style="width: 800px;">
<div id="logo">
<div class="whitetitle" style="margin-top: 70px;">bogotobogo </div>
</div>
<div id="topheader">
<div class="headerbodytext" align="left"><br />
<strong>Bogotobogo</strong><br />
contact@bogotobogo.com </div>
<div class="smallgraytext" id="toplinks"><a href="../index.html">Home</a>
| <a href="../sitemap.html">Sitemap</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="menu">
<div class="smallwhitetext" style="padding: 9px;" align="right"><a
 href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">Products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="submenu">
<div class="smallgraytext" style="padding: 9px;" align="right">
<a href="../gif.html">Gif</a> 
|<a href="../java_applet.html">JavaApplet/Web Start</a>
| <a href="../flash.html">Flash</a>
| <a href="../shockwave.html">ShockWave</a>
| <a href="../svg.html">SVG</a>
| <a href="../iPhone.html">iPhone/iPad</a>
| <a href="../android.html">Android</a>
| <a href="../OnHTML5.html">HTML5</a>
| <a href="../Algorithms/algorithms.html">Algorithms</a>
| <a href="../News/NewsMain.html">News</a>
| <a href="../cplusplus/cpptut.html">C++</a>
| <a href="../Java/tutorial/on_java.html">Java</a>
| <a href="../php/phptut.html">PHP</a>
| <a href="../DesignPatterns/introduction.html">Design Patterns</a>
| <a href="../python/pytut.html">Python</a> 
| <a href="../CSharp/.netframework.html">C#</a>
| <a href="../forums.html">Forums</a> 
| <a href="../VisualBasicSQL/introduction.html">Visual Basic</a>
</div>
</div>

<div id="contenttext">
<br />
<!-- Use of this code assumes agreement with the Google Custom Search Terms of Service. -->
<!-- The terms of service are available at http://www.google.com/cse/docs/tos.html -->
<form name="cse" id="searchbox_demo" action="http://www.google.com/cse">
  <input type="hidden" name="cref" value="" />
  <input type="hidden" name="ie" value="utf-8" />
  <input type="hidden" name="hl" value="" />
  <input name="q" type="text" size="40" />
  <input type="submit" name="sa" value="Search" />
</form>
<script type="text/javascript" src="http://www.google.com/cse/tools/onthefly?form=searchbox_demo&lang="></script>



<br /><br />
<div style="padding: 10px;"><span class="titletext">C++ Tutorial - Operator Overloading</span></div>

<div id="bookmarkshare">
<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script>
<a class="addthis_button" href="http://www.addthis.com/bookmark.php?v=250&amp;username=khhong7"><img src="http://s7.addthis.com/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=khhong7"></script>
</div>


<img src="../images/cplusplus/cpp_logo.jpg" alt="cplusplus logo"/>

<div class="bodytext" style="padding: 12px;" align="justify"> 
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a></li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors (Function Objects)</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL)</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="stl4_algorithms.html">Standard Template Library (STL) IV - Algorithms</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
</div>

<br />
<br />
<img src="images/operatoroverloading/BakDuSan.png" alt="BakDuSan"/>
<br />
<br />


<br />
<div class="bodytext" style="padding: 12px;" align="justify">
<div class="subtitle" id="OperatorOverloading">Operator Overloading</div>
<p>Operator overloading extends the overloading concept to operators so that we can assign new meanings to C++ operators. It lets us extend operator overloading to user-defined types. That is by allowing us to use the "+" to add two objects. The compiler determines which definition of addition to use depending on the number and type of operands. Overloaded operators can often make code look more natural. </p>
<p>To overload an operator, we use a special function, <strong>operator function</strong>. For example, when we overload "+":</p>
<pre>
operator+(argument_list)
</pre>
<p>Suppose, for example, that we have a <strong>MyComplex</strong> class for which we define an <strong>operator+()</strong> member function to overload the <strong>+</strong> operator so that it adds one complex number to another complex number. Then, if <strong>c1, c2, c3</strong> are all objects of <strong>MyComplex</strong> class, we can write this:</p>
<pre>
c3 = c1 + c2;
</pre>
<p>The compiler, recognizing the operands as belonging to the <strong>MyComplex</strong> class, replaces the operator with the corresponding operator function:</p>
<pre>
c3 = c1.operator+(c2);
</pre>
<p>The function then used the <strong>c1</strong> object which invokes the method, and the <strong>c2</strong> object is passed as an argument to calculate the sum, and returns it. Note that we used assignment operator <strong>=</strong> which is also need to be overload.</p>
<br />
<br />

<div class="subtitle" id="OverloadingAssignment">Overloading '='</div>
<p>In this section we'll learn how to overload the assignment (=) operator between two objects of the Complex class. </p>
<p>Let's look at the following code:</p>
<pre>
class MyComplex
{
private:
	double real, imag;
public:
	MyComplex(){
		real = 0; 
		imag = 0;
	}

	MyComplex(double r, double i) {
		real = r;
		imag = i;
	}

	double getReal() const {
		return real;
	}

	double getImag() const {
		return imag;
	}

	<font color="red">MyComplex & operator=(const MyComplex &);</font>
};
<font color="red">
MyComplex & MyComplex::operator=(const MyComplex& c) {
	real = c.real;
	imag = c.imag;
	return *this;
}
</font>
</pre>

<pre>
#include &lt;iostream&gt;

int main()
{
	using namespace std;

	MyComplex c1(5,10);
	MyComplex c2(50,100);
	cout << "c1= " << c1.getReal() << "+" << c1.getImag() << "i" << endl;
	cout << "c2= " << c2.getReal() << "+" << c2.getImag() << "i" << endl;
	c2 = c1;
	cout << "assign c1 to c2:" << endl; 
	cout << "c2= " << c2.getReal() << "+" << c2.getImag() << "i" << endl;
}
</pre>
<p>We get the output as expected:</p>
<pre>
c1= 5+10i
c2= 50+100i
assign c1 to c2:
c2= 5+10i
</pre>
<br />
<br />


<div class="subtitle" id="OverloadingAddition">Overloading '+'</div>
<p>In this section we'll learn how to overload the addition (+) operator between two objects of the Complex class. </p>
<p>Let's look at the following code which has '+' additional overloading function:</p>
<pre>
class MyComplex
{
private:
	double real, imag;
public:
	MyComplex(){
		real = 0; 
		imag = 0;
	}

	MyComplex(double r, double i) {
		real = r;
		imag = i;
	}

	double getReal() const {
		return real;
	}

	double getImag() const {
		return imag;
	}

	MyComplex & operator=(const MyComplex &);
	<font color="red">MyComplex & operator+(const MyComplex& );</font>

};

MyComplex & MyComplex::operator=(const MyComplex& c) {
	real = c.real;
	imag = c.imag;
	return *this;
}
<font color="red">
MyComplex & MyComplex::operator+(const MyComplex& c) {
	real += c.real;
	imag += c.imag;
	return *this;
}</font>

#include &lt;iostream&gt;

int main()
{
	using namespace std;

	MyComplex c1(5,10);
	MyComplex c2(50,100);
	cout << "c1= " << c1.getReal() << "+" << c1.getImag() << "i" << endl;
	cout << "c2= " << c2.getReal() << "+" << c2.getImag() << "i" << endl;
	c2 = c1;
	cout << "assign c1 to c2:" << endl; 
	cout << "c2= " << c2.getReal() << "+" << c2.getImag() << "i" << endl;
	cout << endl;

	MyComplex c3(10,100);
	MyComplex c4(20,200);
	cout << "c3= " << c3.getReal() << "+" << c3.getImag() << "i" << endl;
	cout << "c4= " << c4.getReal() << "+" << c4.getImag() << "i" << endl;
	MyComplex c5 = c3 + c4;
	cout << "adding c3 and c4" << endl;
	cout << "c3= " << c3.getReal() << "+" << c3.getImag() << "i" << endl;
	cout << "c4= " << c4.getReal() << "+" << c4.getImag() << "i" << endl;
	cout << "c5= " << c5.getReal() << "+" << c5.getImag() << "i" << endl;
}
</pre>
<P>Note that when we're using '+' for the object of MyComplex type,<br />
<pre>
c5 = c3 + c4;
</pre>
actually, we are calling a function something like this.<br />
<pre>
c5 = c3.operator+(c4)
</pre>
<p>Output of the code above is:</p>
<pre>
c1= 5+10i
c2= 50+100i
assign c1 to c2:
c2= 5+10i

c3= 10+100i
c4= 20+200i
adding c3 and c4
c3= 30+300i
c4= 20+200i
c5= 30+300i
</pre>
<p>We got the right result at least for <strong>c5</strong>. But the value of <strong>c3</strong> has been changed. </p>
<p>What happened?</p>
<p>Let look at the code overloading '+'.</p>
<pre>
MyComplex & MyComplex::operator+(const MyComplex& c) {
	real += c.real;
	imag += c.imag;
	return *this;
}
</pre>
<p>As it turned out, the operation inside the function returning the reference to <strong>c3</strong> object which has been changed. </p>
<p>So, let's rewrite the overloading function.</p>
<pre>
const MyComplex operator+(const MyComplex & );

const MyComplex MyComplex::operator+(const MyComplex& c) {
	MyComplex temp;
	temp.real = this->real + c.real;
	temp.imag = this->imag + c.imag;
	return temp;
}
</pre>
<p>Note that this doesn't return <strong>Complex &</strong>, but instead returns a <strong>const Complex</strong> class variable. As you can see, the implementation is a little bit different from the previous example. Here, we're not returning <strong>*this</strong>. Instead, we're creating a temporary variable and assigning the results of the addition to <strong>temp</strong>. This explains why the function returns const Complex and not Complex &. In other words, the function creates a new <strong>MyComplex</strong> object <strong>temp</strong> that represents the sum of the other two <strong>MyComplex</strong> objects. Returning the object creates a copy of the object that the calling function can use. If the return type were <strong>MyComplex &</strong>, however, the reference would be the <strong>temp</strong> object. But the <strong>temp</strong> object is a local variable and is destroyed when the function terminates, so the reference would be a reference to a nonexisting object. Using a <strong>MyComplex</strong> return type, however, means the program constructs a <strong>copy</strong> of <strong>MyComplex</strong> object before destroying it, and the calling function gets the copy.</p>
<p>Why we're returning <strong>const</strong>? Look <a href="object_returning.html#aconstobject" target="_blank">Object Returning</a>.</p>

<p>Then, we'll get the right answer.</p>
<pre>
c1= 5+10i
c2= 50+100i
assign c1 to c2:
c2= 5+10i

c3= 10+100i
c4= 20+200i
adding c3 and c4
c3= 10+100i
c4= 20+200i
c5= 30+300i
</pre>
<br />
<br />


<div class="subtitle" id="OverloadingFriend">Overloading '+' using Friend Function</div>
<p>We get the same result if we use a friend function which is global and not a member of our <strong>MyComplex</strong> class.</p>
<p>Since this function will need to access the <strong>private</strong> members of <strong>MyComplex</strong>, we'll need to declare it as a <strong>friend</strong> function. </p>
<pre>
friend const MyComplex operator+(const MyComplex&, const MyComplex&);
</pre>
<p>The prototype has two implications:</p>
<ul>
   <li>Although the <strong>operator+()</strong> function is not a member function, it has the same access rights as a member function.</li>
   <li>Although the <strong>operator+()</strong> function is declared in the class declaration, it is not a member function. So it isn't invoked by using the membership operator.</li>
</ul>
<p>Our revised code is:</p>
<pre>
class MyComplex
{
private:
	double real, imag;
public:
	MyComplex(){
		real = 0; 
		imag = 0;
	}

	MyComplex(double r, double i) {
		real = r;
		imag = i;
	}

	double getReal() const {
		return real;
	}

	double getImag() const {
		return imag;
	}

	MyComplex & operator=(const MyComplex &);
	<font color="red">
	friend const 
		MyComplex operator+(const MyComplex&, const MyComplex&); </font>
};

MyComplex & MyComplex::operator=(const MyComplex& c) {
	real = c.real;
	imag = c.imag;
	return *this;
}

/* This is not a member function of MyComplex class */
<font color="red">const MyComplex operator+(const MyComplex& c1, const MyComplex& c2) {
	MyComplex temp;
	temp.real = c1.real + c2.real;
	temp.imag = c1.imag + c2.imag;
	return temp;
}
</font>
#include &lt;iostream&gt;

int main()
{
	using namespace std;

	MyComplex c1(5,10);
	MyComplex c2(50,100);
	cout << "c1= " << c1.getReal() << "+" << c1.getImag() << "i" << endl;
	cout << "c2= " << c2.getReal() << "+" << c2.getImag() << "i" << endl;
	c2 = c1;
	cout << "assign c1 to c2:" << endl; 
	cout << "c2= " << c2.getReal() << "+" << c2.getImag() << "i" << endl;
	cout << endl;

	MyComplex c3(10,100);
	MyComplex c4(20,200);
	cout << "c3= " << c3.getReal() << "+" << c3.getImag() << "i" << endl;
	cout << "c4= " << c4.getReal() << "+" << c4.getImag() << "i" << endl;
	MyComplex c5 = c3 + c4;
	cout << "adding c3 and c4" << endl;
	cout << "c3= " << c3.getReal() << "+" << c3.getImag() << "i" << endl;
	cout << "c4= " << c4.getReal() << "+" << c4.getImag() << "i" << endl;
	cout << "c5= " << c5.getReal() << "+" << c5.getImag() << "i" << endl;
}
</pre>
<p>Note that, in the above example, we used one of the two forms for overloading <strong>operator+()</strong>.</p>
<p>What we used was nonmember version:</p>
<pre>
MyComplex operator+(const MyComplex& c1, const MyComplex& c2);
</pre>
<p>But there is another form which is member version:</p>
<pre>
MyComplex operator+(const MyComplex& c1);
</pre>
<p>For the member function version, one is passed implicitly via the <strong>this</strong> pointer and the second is passed explicitly as a function argument. For the friend version, which is nonmember version, both are passed as argument. </p>
<p>Either of these two prototypes matches the express <strong>c1+c2</strong>, where <strong>c1</strong> and <strong>c2</strong> are type <strong>MyComplex</strong> objects. That is, the compiler can convert the statement</p>
<pre>
c3 = c1 + c2;
</pre>
<p>to either of the following:</p>
<pre>
c3 = opetator+(c1,c2);     // nonmember function
c3 = c1.operator+(c2);     // member function
</pre>
<br />
<br />


<div class="subtitle" id="OverloadingOutputOperator">Overloading the << Operator </div>
<p>Output streams use the <strong><<</strong> operator for standard types. We can also overload the <strong><<</strong>  operator for our own classes.</p>
<p>Actually, the <strong><<</strong> is left shift bit manipulation operator. But the <strong>ostream</strong> class overloads the operator, converting it into an output tool. The <strong>cout</strong> is an <strong>ostream</strong> object and that it is smart enough to recognize all the basic C++ types. That's because the <strong>ostream</strong> class declaration includes an overloaded <strong>operator<<()</strong> definition for each of the basic types.</p>

<pre>
#include &lt;iostream&gt;
using namespace std;

class MyComplex
{
private:
	double real, imag;
public:
	MyComplex(){
		real = 0; 
		imag = 0;
	}

	MyComplex(double r, double i) {
		real = r;
		imag = i;
	}

	double getReal() const {
		return real;
	}

	double getImag() const {
		return imag;
	}

	MyComplex & operator=(const MyComplex &);
	const MyComplex operator+(const MyComplex & );
	MyComplex & operator++(void);
	MyComplex  operator++(int);

	/*friend const 
		MyComplex operator+(const MyComplex&, const MyComplex&); */

	<font color="red">friend ostream& operator<<(ostream& os, const MyComplex& c);</font>
};

MyComplex & MyComplex::operator=(const MyComplex& c) {
	real = c.real;
	imag = c.imag;
	return *this;
}

const MyComplex MyComplex::operator+(const MyComplex& c) {
	MyComplex temp;
	temp.real = this->real + c.real;
	temp.imag = this->imag + c.imag;
	return temp;
}

//pre-increment
MyComplex & MyComplex::operator++() {
	real++;
	imag++;
	return *this;
}

//post-increment
MyComplex MyComplex::operator++(int) {
	    MyComplex temp = *this;
	    real++;
	    imag++;
	    return temp;
}

/* This is not a member function of MyComplex class */
/*
const MyComplex operator+(const MyComplex& c1, const MyComplex& c2) {
	    MyComplex temp;
	    temp.real = c1.real + c2.real;
	    temp.imag = c1.imag + c2.imag;
	    return temp;
}*/


<font color="red">ostream& operator<<(ostream &os, const MyComplex& c) {
	os << c.real << '+' << c.imag << 'i' << endl;
	return os;
}</font>

int main()
{
	MyComplex c1(5,10);
	cout << "c1 = " << c1.getReal() << "+" << c1.getImag() << "i" << endl;

	cout << "Using overloaded << " << endl;
	<font color="red">cout << "c1 = " << c1 << endl;</font>
}
</pre>
<p>Output is:</p>
<pre>
c1 = 5+10i
Using overloaded <<
c1 = 5+10i
</pre>
<p>Note that we just used:</p>
<pre>
cout << "c1 = " << c1 << endl;
</pre>
<p>Note that when we do<p>
<pre>
cout << c1;
</pre>
<p>it becomes the following function call:</p>
<pre>
operator<<(cout, c1);
</pre>
<br />
<br />


<div class="subtitle" id="OverloadingIncrementOperator">Increment/Decrement '++/--' Operator Overloading</div>
<p>In this section, we'll learn how to overload increment and decrement operators (++ and --). We'll put a focus on the increment operators since the decrement operators are working in the same way. There are two types of increment operators actually: <strong> pre-increment(++i)</strong> and <strong>post-increment(i++)</strong>. </p>
<p>Here is the modified code with the overloaded increment functions.</p>
<pre>
class MyComplex
{
private:
	double real, imag;
public:
	MyComplex(){
		real = 0; 
		imag = 0;
	}

	MyComplex(double r, double i) {
		real = r;
		imag = i;
	}

	double getReal() const {
		return real;
	}

	double getImag() const {
		return imag;
	}

	MyComplex & operator=(const MyComplex &);
	const MyComplex operator+(const MyComplex & );
	<font color="red">MyComplex & operator++(void);
	MyComplex  operator++(int);</font>

/*	friend const 
		MyComplex operator+(const MyComplex&, const MyComplex&); */
	
};

MyComplex & MyComplex::operator=(const MyComplex& c) {
	real = c.real;
	imag = c.imag;
	return *this;
}

const MyComplex MyComplex::operator+(const MyComplex& c) {
	MyComplex temp;
	temp.real = this->real + c.real;
	temp.imag = this->imag + c.imag;
	return temp;
}

//pre-increment
<font color="red">MyComplex & MyComplex::operator++() {
	real++;
	imag++;
	return *this;
}</font>

//post-increment
<font color="red">MyComplex MyComplex::operator++(int) {
	    MyComplex temp = *this;
	    real++;
	    imag++;
	    return temp;
}</font>

/* This is not a member function of MyComplex class */
/*
const MyComplex operator+(const MyComplex& c1, const MyComplex& c2) {
	    MyComplex temp;
	    temp.real = c1.real + c2.real;
	    temp.imag = c1.imag + c2.imag;
	    return temp;
}*/

#include &lt;iostream&gt;

int main()
{
	using namespace std;

	MyComplex c1(5,10);
	MyComplex c2(50,100);
	cout << "c1= " << c1.getReal() << "+" << c1.getImag() << "i" << endl;
	cout << "c2= " << c2.getReal() << "+" << c2.getImag() << "i" << endl;
	c2 = c1;
	cout << "assign c1 to c2:" << endl; 
	cout << "c2= " << c2.getReal() << "+" << c2.getImag() << "i" << endl;
	cout << endl;

	MyComplex c3(10,100);
	MyComplex c4(20,200);
	cout << "c3= " << c3.getReal() << "+" << c3.getImag() << "i" << endl;
	cout << "c4= " << c4.getReal() << "+" << c4.getImag() << "i" << endl;
	MyComplex c5 = c3 + c4;
	cout << "adding c3 and c4" << endl;
	cout << "c3= " << c3.getReal() << "+" << c3.getImag() << "i" << endl;
	cout << "c4= " << c4.getReal() << "+" << c4.getImag() << "i" << endl;
	cout << "c5= " << c5.getReal() << "+" << c5.getImag() << "i" << endl;
	cout << endl;
	++c5;
	cout << "c5= " << c5.getReal() << "+" << c5.getImag() << "i" << endl;
	c5++;
	cout << "c5= " << c5.getReal() << "+" << c5.getImag() << "i" << endl;
}
</pre>
<br />
<p>The output is:</p>
<pre>
c1= 5+10i
c2= 50+100i
assign c1 to c2:
c2= 5+10i

c3= 10+100i
c4= 20+200i
adding c3 and c4
c3= 10+100i
c4= 20+200i
c5= 30+300i

c5= 31+301i
c5= 32+302i
</pre>
<p>There is one problem with defining both the prefix and postfix opetators: They each take the same number and type of parameters. Normal overloading cannot distinguish between whether the operator we're defining is the prefix version or the postfix.</p>
<p>To solve this problem, the <strong>postfix</strong> operator function take an extra parameter of the <strong>int</strong>. When we use the postfix operator, the compiler supplies <strong>0</strong> as the argument for this parameter. Although our postfix function could use this extra parameter, it usually should not. That parameter is not needed for the work normally performed by a postfix operator. Its sole purpose is to distinguish the definition of the postfix function from the prefix version.</p>
<br />
<p>The increment(++) and decrement(--) operators are most often implemented for class, such as iterators, that provide pointerlike behavior on the elements of a sequence. In the example below, we define a class that points to an array and provides access to the elements in the array.</p>
<pre>
#include &lt;iostream&gt;

class SmartPtr
{
public:
	SmartPtr(int *b, int *e):beg(b), end(e), curr(b) {}
	SmartPtr operator++(int);
	SmartPtr& operator++();
	int* getCurrent() {
		return curr;
	}
private:
	int *beg;
	int *end;
	int *curr;
};

<font color="red">
SmartPtr& SmartPtr::operator++()
{
	if(curr == end)
		throw "increment past the end";
	++curr;
	return *this;
}

SmartPtr SmartPtr::operator++(int)
{
	SmartPtr ret(*this);
	++*this;
	return ret;
}
</font>

int main( ) 
{ 
	using namespace std;
	int a[] = {1,2,3,4,5};
	try {
		SmartPtr *ptr = new SmartPtr(a,a+5);
		cout << *(ptr->getCurrent()) << endl;
		(*ptr)++;
		cout << *(ptr->getCurrent()) << endl;
	}
	catch (const char* e) {
		cout << "exception: " << e << endl;
	}
	return 0; 
}
</pre>
<br />
<p>Let's look at the postfix version. It is a bit more involved than the prefix operators. They should remember the current state of the object before incrementing the object. This operator defines a local SmartPtr, which is initialized as a copy of <strong>*this</strong>. In other words, the variable <strong>ret</strong> is a copy of the current state of this object.</p>
Having kept a copy of the current state, the operator calls its own prefix operator to do the increment:</p>
<pre>
++*this;
</pre>
<p>calls the <strong>SmartPtr</strong> prefix increment operator on this object. That operator checks that the increment is safe and either increments <strong>curr</strong> or throws an exception. If no exception was thrown, the postfix function completes by returning the stored copy in <strong>ret</strong>. Therefore, after the return, <strong>the object itself has been advanced, buit the value returned reflects the original, unincremented value.</strong></p>
<pre>
SmartPtr& SmartPtr::operator++()
{
	if(curr == end)
		throw "increment past the end";
	++curr;
	return *this;
}
</pre>


<br />
<br />
<img src="images/operatoroverloading/UngDo.png" alt="UngDo"/>
<br />
<br />


<br /><br />
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a></li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors (Function Objects)</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL)</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="stl4_algorithms.html">Standard Template Library (STL) IV - Algorithms</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
<br /><br />




<br />


<br />
<br />
<br />


</div>
</div>
<div class="smallgraytext" id="footer"><a href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="#">Contact Us</a>
| Bogotobogo &copy; 2011 | <a target="_blank" href="http://www.bogotobogo.com">Bogotobogo </a>
</div>
</div>
</div>
</body>
</html>
